package org.ibase4j.system.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ibase4j.jwt.utils.StringUtils;
import org.ibase4j.system.model.*;
import org.ibase4j.system.service.SysAuthorizeService;
import org.ibase4j.system.service.SysCacheService;
import org.ibase4j.system.service.SysDicService;
import org.ibase4j.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import top.ibase4j.core.base.AbstractController;
import top.ibase4j.core.exception.IllegalParameterException;

import java.util.*;

/**
 * 权限管理
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:14:05
 */
@RestController
@Api(value = "权限管理", description = "权限管理")
public class SysAuthorizeController extends AbstractController {
    SysAuthorizeService authorizeService;
    SysCacheService sysCacheService;
    SysMenuService sysMenuService;
    @Autowired
    private SysDicService sysDicService;

    @ApiOperation(value = "获取用户菜单编号")
    @RequestMapping(value = "/user/read/menu")
    @RequiresPermissions("sys.permisson.userMenu.read")
    public Object getUserMenu(ModelMap modelMap, @RequestBody SysUserMenu param) {
        List<Long> userMenuIdList = authorizeService.queryUserMenuIdsList(param.getUserId());
        modelMap.put("userMenuIdList",userMenuIdList);
        return setSuccessModelMap(modelMap);
    }



    @ApiOperation(value = "修改用户菜单")
    @RequestMapping(value = "/user/update/menu")
    @RequiresPermissions("sys.permisson.userMenu.update")
    public Object userMenu(ModelMap modelMap, @RequestBody SysUserMenu param) {
        Long userId = param.getId();
        if (userId != null  && userId.longValue() != param.getId()) throw new IllegalParameterException("参数错误.");
        Long currentUserId = getCurrUser().getId();
        List<SysUserMenu> sysUserMenuList = new ArrayList<>();
        if(StringUtils.isNotEmpty(param.getIds())){
            List<Integer> menuIds = param.getIds();
            for (Integer menuId : menuIds) {
                if(menuId == null)continue;
                SysUserMenu sysUserMenu = new SysUserMenu();
                sysUserMenu.setPermission("read");
                sysUserMenu.setUserId(userId);
                sysUserMenu.setMenuId(menuId.longValue());
                sysUserMenu.setCreateBy(currentUserId);
                sysUserMenu.setUpdateBy(currentUserId);
                sysUserMenu.setCreateTime(new Date());
                sysUserMenu.setUpdateTime(new Date());
                sysUserMenuList.add(sysUserMenu);
            }
        }
        authorizeService.updateUserMenu(sysUserMenuList);
        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "获取人员操作权限")
    @RequestMapping(value = "user/read/permission")
    @RequiresPermissions("sys.permisson.user.read")
    public Object queryUserPermissions(ModelMap modelMap,  SysUserMenu record) {
//        List<?> menuIds = authorizeService.queryUserPermissions(record);
        List<SysMenu> allMenusList = sysMenuService.queryAllMenus(new HashMap<>());
        List<SysMenu> sysMenuWhtiHandleList = sysMenuService.queryAllSysMenuWithHandleList(allMenusList);
        return setSuccessModelMap(modelMap, sysMenuWhtiHandleList);
    }

    @ApiOperation(value = "修改用户操作权限")
    @RequestMapping(value = "/user/update/permission")
    @RequiresPermissions("sys.permisson.user.update")
    public Object updateUserPermission(ModelMap modelMap, @RequestBody List<SysUserMenu> list) {
        Long userId = null;
        Long currentUserId = getCurrUser().getId();
        for (SysUserMenu sysUserMenu : list) {
            if (sysUserMenu.getUserId() != null) {
                if (userId != null && sysUserMenu.getUserId() != null
                        && userId.longValue() != sysUserMenu.getUserId()) {
                    throw new IllegalParameterException("参数错误.");
                }
                userId = sysUserMenu.getUserId();
            }
            sysUserMenu.setCreateBy(currentUserId);
            sysUserMenu.setUpdateBy(currentUserId);
            sysUserMenu.setCreateTime(new Date());
            sysUserMenu.setUpdateTime(new Date());
        }
        authorizeService.updateUserPermission(list);
        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "获取用户角色")
    @RequestMapping(value = "user/read/role")
    @RequiresPermissions("sys.permisson.userRole.read")
    public Object getUserRole(ModelMap modelMap,  SysUserRole param) {
        List<?> menus = authorizeService.getRolesByUserId(param.getUserId());
        return setSuccessModelMap(modelMap, menus);
    }

    @ApiOperation(value = "修改用户角色")
    @RequestMapping(value = "/user/update/role")
    @RequiresPermissions("sys.permisson.userRole.update")
    public Object userRole(ModelMap modelMap,  List<SysUserRole> list) {
        Long userId = null;
        Long currentUserId = getCurrUser().getId();
        for (SysUserRole sysUserRole : list) {
            if (sysUserRole.getUserId() != null) {
                if (userId != null && sysUserRole.getUserId() != null
                        && userId.longValue() != sysUserRole.getUserId()) {
                    throw new IllegalParameterException("参数错误.");
                }
                userId = sysUserRole.getUserId();
            }
            sysUserRole.setCreateBy(currentUserId);
            sysUserRole.setUpdateBy(currentUserId);
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setUpdateTime(new Date());
        }
        authorizeService.updateUserRole(list);
        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "清理缓存")
    @RequiresPermissions("sys.cache.update")
    @RequestMapping(value = "/cache/update", method = RequestMethod.POST)
    public Object flush(ModelMap modelMap, @RequestBody Map<String, String> param) {
        sysCacheService.flush(param);
        return setSuccessModelMap(modelMap);
    }
}
